﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace KeepAccounts.Common.Utilities
{
    public static class StringExtend
    {

        public static string JoinIds(this IEnumerable<string> ids)
        {
            return string.Join(",", ids.Select(s => $"'{s}'"));
        }

        public static string JoinInts(this IEnumerable<int> ids)
        {
            return string.Join(",", ids.Select(s => $"{s}"));
        }
        public static string JoinInts(this IEnumerable<int?> ids)
        {
            return string.Join(",", ids.Select(s => $"{s}"));
        }

        public static string JoinProperties(this IEnumerable<string> ids)
        {
            return string.Join(",", ids);
        }

        public static IEnumerable<string> GetPropertyStrings<T>(string endsWithString) where T : class, new()
        {
            var properties = typeof(T).GetProperties();
            var columns = properties.Select(p => p.Name).Where(s => !string.IsNullOrEmpty(s));
            if (!string.IsNullOrWhiteSpace(endsWithString))
            {
                columns = columns.Where(t => !t.EndsWith(endsWithString));
            }
            return columns.ToList();
        }



        /// <summary>
        /// 去掉中文标签
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string CleanHtml(string strHtml)
        {
            if (string.IsNullOrEmpty(strHtml)) return strHtml;
            //删除脚本
            //Regex.Replace(strHtml, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase)
            strHtml = Regex.Replace(strHtml, "(<script(.+?)</script>)|(<style(.+?)</style>)", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            strHtml = Regex.Replace(strHtml, @" ", "");
            strHtml = Regex.Replace(strHtml, @"\n\s*\n", "\r\n");
            strHtml = strHtml.Replace("&nbsp;", "");
            strHtml = strHtml.Replace("\r", "");
            strHtml = strHtml.Replace("\n", "");
            strHtml = strHtml.Replace("\t", "");

            //删除标签
            var r = new Regex(@"</?[^>]*>", RegexOptions.IgnoreCase);

            Match m;
            for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
            {
                strHtml = strHtml.Replace(m.Groups[0].ToString(), "");
            }
            return strHtml.Trim();
        }

        public static string RandomCode(bool onlyNumber = false, int length = 6)
        {
            length = length < 1 ? 6 : length;
            var availableChars = onlyNumber ? "0123456789" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var id = new char[length];
            Random random = new Random();
            for (var i = 0; i < length; i++)
            {
                id[i] = availableChars[random.Next(0, availableChars.Length)];
            }
            return new string(id);
        }

        public static StringBuilder GetFirstImgUrl(string text)
        {
            StringBuilder str = new StringBuilder();
            string pat = @"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>";
            Regex r = new Regex(pat, RegexOptions.Compiled);
            Match m = r.Match(text.ToLower());
            //int matchCount = 0;
            while (m.Success)
            {
                Group g = m.Groups[2];
                str.Append(g).Append(",");
                m = m.NextMatch();
            }
            return str.Replace("\"", "");
        }

        /// <summary>
        /// 保留小数点有效数字maxAccurate
        /// </summary>
        /// <param name="value"></param>
        /// <param name="maxAccurate"></param>
        /// <returns></returns>
        public static string StringFormat(double value, int maxAccurate = 2)
        {
            var valueStr = value.ToString();
            var temp = valueStr.Split('.');
            if (temp == null || temp.Count() != 2)
            {
                return valueStr;
            }

            if (temp[1].Count() < 2)
            {
                return temp[0] + "." + temp[1];
            }
            return temp[0] + "." + temp[1].Substring(0, 2);
        }

        public static string PhoneReplace(this string input)
        {
            if (string.IsNullOrEmpty(input) || input.Length != 11)
            {
                return string.Empty;
            }
            return input.Remove(3, 4).Insert(3, "****");
        }

        /// <summary>
        /// Check是否包含特殊字符
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool CheckSpecialCharacter(this string input)
        {
            Regex regExp = new Regex("^[\u4E00-\u9FA5A-Za-z0-9_]+$");
            return regExp.IsMatch(input);
        }

        /// <summary>
        /// Check是否包含空格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool CheckContainSpace(this string input)
        {
            if (input.IndexOf(" ") > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 大小写敏感比较。
        /// </summary>
        public static bool CaseSensitiveEquals(this string instance, string comparing)
        {
            if (instance == null && comparing == null)
            {
                return true;
            }
            if ((instance != null && comparing == null) || (instance == null && comparing != null))
            {
                return false;
            }
            return String.CompareOrdinal(instance, comparing) == 0;
        }

        /// <summary>
        /// 大小写忽略比较。
        /// </summary>
        public static bool CaseInsensitiveEquals(this string instance, string comparing)
        {
            if (instance == null && comparing == null)
            {
                return true;
            }
            if ((instance != null && comparing == null) || (instance == null && comparing != null))
            {
                return false;
            }
            return instance.Equals(comparing, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 指示指定的 <see cref="System.String"/> 对象是 null 还是 System.String.Empty 字符串。
        /// </summary>
        public static bool IsNullOrEmpty(this String data)
        {
            return String.IsNullOrEmpty(data);
        }

        /// <summary>
        /// 指示指定的字符串是 null、空还是仅由空白字符组成。
        /// </summary>
        public static bool IsNullOrWhiteSpace(this String data)
        {
            return String.IsNullOrWhiteSpace(data);
        }

        /// <summary>
        /// 	如果指定的 <see cref="System.String"/> 对象字符串是 null、空还是仅由空白字符组成则返回默认值。
        /// </summary>
        public static string IfNullOrWhiteSpace(this string value, string defaultValue)
        {
            return (!value.IsNullOrWhiteSpace() ? value : defaultValue);
        }

        /// <summary>
        /// 	如果指定的 <see cref="System.String"/> 对象是 null 或 System.Empty 字符串则返回默认值。
        /// </summary>
        public static string IfNullOrEmpty(this string value, string defaultValue)
        {
            return (!value.IsNullOrEmpty() ? value : defaultValue);
        }


        public static string ToChineseString(this decimal hits)
        {
            if (hits < 百)
            {
                return hits.ToString("#0.00");
            }
            else if (hits < 万)
            {
                return Math.Floor(hits).ToString();
            }
            else if (hits < 百万)
            {
                return (hits / 万).ToString("#0.00") + "万";
            }
            else if (hits < 亿)
            {
                return Math.Floor(hits / 万).ToString() + "万";
            }
            else
            {
                return (hits / 亿).ToString("#0.00") + "亿";
            }
        }
        public const int 百 = 100;
        public const int 万 = 10000;
        public const int 百万 = 1000000;
        public const int 亿 = 100000000;


        public static string ConvertEngWord(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "#";
            }
            if (input.Length > 1)
            {
                input = input.Substring(0, 1);
            }
            long iCnChar;
            byte[] ZW = System.Text.Encoding.Default.GetBytes(input);
            //如果是字母，则直接返回首字母
            if (ZW.Length == 1)
            {
                if ("abcdefghijklmnopqrstuvwxyz".Contains(input.ToLower()))
                {
                    return input.ToUpper();
                }
                else
                {
                    return "#";
                }
            }
            else
            {
                int i1 = (short)(ZW[0]);
                int i2 = (short)(ZW[1]);
                iCnChar = i1 * 256 + i2;
            }
            if ((iCnChar >= 45217) && (iCnChar <= 45252))
            {
                return "A";
            }
            else if ((iCnChar >= 45253) && (iCnChar <= 45760))
            {
                return "B";
            }
            else if ((iCnChar >= 45761) && (iCnChar <= 46317))
            {
                return "C";
            }
            else if ((iCnChar >= 46318) && (iCnChar <= 46825))
            {
                return "D";
            }
            else if ((iCnChar >= 46826) && (iCnChar <= 47009))
            {
                return "E";
            }
            else if ((iCnChar >= 47010) && (iCnChar <= 47296))
            {
                return "F";
            }
            else if ((iCnChar >= 47297) && (iCnChar <= 47613))
            {
                return "G";
            }
            else if ((iCnChar >= 47614) && (iCnChar <= 48118))
            {
                return "H";
            }
            else if ((iCnChar >= 48119) && (iCnChar <= 49061))
            {
                return "J";
            }
            else if ((iCnChar >= 49062) && (iCnChar <= 49323))
            {
                return "K";
            }
            else if ((iCnChar >= 49324) && (iCnChar <= 49895))
            {
                return "L";
            }
            else if ((iCnChar >= 49896) && (iCnChar <= 50370))
            {
                return "M";
            }
            else if ((iCnChar >= 50371) && (iCnChar <= 50613))
            {
                return "N";
            }
            else if ((iCnChar >= 50614) && (iCnChar <= 50621))
            {
                return "O";
            }
            else if ((iCnChar >= 50622) && (iCnChar <= 50905))
            {
                return "P";
            }
            else if ((iCnChar >= 50906) && (iCnChar <= 51386))
            {
                return "Q";
            }
            else if ((iCnChar >= 51387) && (iCnChar <= 51445))
            {
                return "R";
            }
            else if ((iCnChar >= 51446) && (iCnChar <= 52217))
            {
                return "S";
            }
            else if ((iCnChar >= 52218) && (iCnChar <= 52697))
            {
                return "T";
            }
            else if ((iCnChar >= 52698) && (iCnChar <= 52979))
            {
                return "W";
            }
            else if ((iCnChar >= 52980) && (iCnChar <= 53640))
            {
                return "X";
            }
            else if ((iCnChar >= 53689) && (iCnChar <= 54480))
            {
                return "Y";
            }
            else if ((iCnChar >= 54481) && (iCnChar <= 55289))
            {
                return "Z";
            }
            else
            {
                return ("#");
            }
        }
        /// <summary>
        /// 首字母小写写
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string FirstCharToLower(this string input)
        {
            if (String.IsNullOrEmpty(input))
                return input;
            string str = input.First().ToString().ToLower() + input.Substring(1);
            return str;
        }

        /// <summary>
        /// 首字母大写
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string FirstCharToUpper(this string input)
        {
            if (String.IsNullOrEmpty(input))
                return input;
            string str = input.First().ToString().ToUpper() + input.Substring(1);
            return str;
        }

        /// <summary>
        /// 生成积分商品订单编号
        /// </summary>
        /// <returns></returns>
        public static string GetCreditOrderNumber()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }



        /// <summary>
        /// 替换html中的url
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceUrl(this string str, string domain)
        {

            if (!string.IsNullOrEmpty(str))
            {
                Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""\s]?)(?<href>[^'""\s]*)\1[^>]*?>");
                MatchCollection match = reg.Matches(str);
                List<string> hrefList = new List<string>();
                foreach (Match m in match)
                {
                    if (!hrefList.Contains(m.Groups["href"].Value) && !m.Groups["href"].Value.ToLower().StartsWith("http://") && !m.Groups["href"].Value.ToLower().StartsWith("https://"))
                        hrefList.Add(m.Groups["href"].Value);
                }

                foreach (var href in hrefList)
                {
                    if (href.StartsWith("/"))
                    {
                        str = str.Replace(href, domain + href);
                    }
                    else
                    {
                        str = str.Replace(href, domain + href);
                    }
                }


                reg = new Regex(@"(?is)<img[^>]*?src=(['""\s]?)(?<src>[^'""\s]*)\1[^>]*?>");
                match = reg.Matches(str);
                hrefList = new List<string>();
                foreach (Match m in match)
                {
                    if (!hrefList.Contains(m.Groups["src"].Value) && !m.Groups["src"].Value.ToLower().StartsWith("http://") && !m.Groups["src"].Value.ToLower().StartsWith("https://"))
                        hrefList.Add(m.Groups["src"].Value);
                }

                foreach (var href in hrefList)
                {
                    if (href.StartsWith("/"))
                    {
                        str = str.Replace(href, domain + href);
                    }
                    else
                    {
                        str = str.Replace(href, domain + href);
                    }
                }
                return str;
            }

            return "";
        }


    }
}
